package com.woniuxy.xiangruicommonutilserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.xiangruicommonutilserver.service.IMinioService;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.errors.InvalidEndpointException;
import io.minio.messages.Item;
import io.minio.policy.PolicyType;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @author: masterhai
 * @date: 2021/4/5:19:04
 * @description:
 */
@Slf4j
@Service
public class MinioServiceImpl implements IMinioService {
    @Value("${my.minio.accesskey}")
    private String accesskey;
    @Value("${my.minio.secretkey}")
    private String secretkey;
    @Value("${my.minio.endpoint}")
    private String endpoint;

    @Override
    public ResultBean saveFile (String bucketName, MultipartFile file) {
        //定义返回的文件路径
        String fileUrl = null;
        //上传文件流
        InputStream inputStream = null;
        try {
            //使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = new MinioClient(endpoint, accesskey, secretkey);
            // 检查存储桶是否已经存在.不存在则创建新桶
            if (! minioClient.bucketExists(bucketName)) {
                // 创建一个存储桶，用于存储文件。
                minioClient.makeBucket(bucketName);
            }
            //设置桶的访问策略
            minioClient.setBucketPolicy(bucketName, "*", PolicyType.READ_WRITE);
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件后缀
            filename = filename.substring(filename.lastIndexOf("."));
            //文件名添加唯一值,避免同名覆盖
            filename = UUID.randomUUID().toString().replaceAll("-", "")  + filename;
            //根据日期管理文件路径 2021/01/31/文件名
            filename = new DateTime().toString("yyyy/MM/dd") + "/" + filename;
            try {
                minioClient.putObject(bucketName, filename, file.getInputStream(), file.getSize(), file.getContentType());
                //拼接返回的文件路径  http://106.13.1.48:9000/images/2021/04/05/d8e8e6a8b6fb4e2ea5dcf78c2c0c811b03.png
                fileUrl = new StringBuilder().append(endpoint).append("/").append(bucketName).append("/").append(filename).toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            log.error("Error occurred: " + e);
            return ResultBean.builder().code(500).msg("文件上传失败,请联系管理员").build();
        }
        return ResultBean.builder().code(200).msg("文件上传成功").data(fileUrl).build();
    }

    @Override
    public void removeFile (String bucketName, String objectName) {
        try {
            MinioClient minioClient = new MinioClient(endpoint, accesskey, secretkey);
            //截取文件名,将桶名之前的都去除掉
            int index = objectName.indexOf(bucketName);
            String fileName = objectName.substring(index + bucketName.length());
            minioClient.removeObject(bucketName, fileName);
        } catch (InvalidEndpointException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public ResultBean listFileByBucket (String bucketName) {
        ArrayList<String> files = new ArrayList<>();
        try {
            MinioClient minioClient = new MinioClient(endpoint, accesskey, secretkey);
            Iterable<Result<Item>> results = minioClient.listObjects(bucketName);
            for (Result<Item> result : results) {
                Item item = result.get();
                //log.info(item.lastModified() + ", " + item.size() + ", " + item.objectName());
                //将文件名拼接上路径
                files.add(endpoint + "/" + bucketName + "/" + item.objectName());
            }
        } catch (InvalidEndpointException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBean.builder().code(200).msg("查询成功").data(files).build();
    }
}
